"""SSE事件发送辅助模块"""
import json
import numpy as np


class NumpyEncoder(json.JSONEncoder):
    """自定义JSON编码器，支持numpy数据类型"""
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, (np.floating, np.float32, np.float64)):
            return float(obj)
        elif isinstance(obj, (np.integer, np.int32, np.int64)):
            return int(obj)
        elif isinstance(obj, np.bool_):
            return bool(obj)
        return super().default(obj)


SSE_EVENT_PREFIX = "__SSE_EVENT__"


def send_sse_event(event_type: str, data: dict, tag: str = "sse"):
    """发送SSE事件给前端
    
    Args:
        event_type: 事件类型（如 "chart", "knowledge_search", "plan" 等）
        data: 要发送的数据字典
        tag: 日志标签，默认"sse"
    """
    try:
        event_payload = {
            "event_type": event_type,
            "data": data
        }
        sse_message = f"{SSE_EVENT_PREFIX}{json.dumps(event_payload, cls=NumpyEncoder, ensure_ascii=False)}"
        print(sse_message)
    except Exception as e:
        print(f"[{tag}] ⚠️ 发送事件失败: {str(e)}")
